package com.example.show_auto.utils

import com.example.show_auto.data.*
import com.example.show_auto.ui.pages.RecipeLimitsState
import com.example.show_auto.ui.pages.UltimateSkillsState

/**
 * 一键查询计算器
 * 根据选择的未修炼厨师，自动生成满足其修炼任务的最优组合
 */
object OneClickQueryCalculator {

    // 当前查询使用的光环厨师设置
    private var currentEnabledAuraChefs: Set<String> = emptySet()
    
    // 当前分配的菜谱光环厨师信息
    private var currentRecipeAuraChefs: Map<Recipe, List<Chef>> = emptyMap()
    
    /**
     * 一键查询结果
     */
    /**
     * 菜谱分配结果
     */
    data class RecipeAllocation(
        val recipes: List<Recipe>, // 9个菜谱
        val portions: List<Int>, // 对应的实际分配份数
        val updatedChefs: List<Chef> = emptyList() // 更新后的厨师组合（包含光环厨师）
    )

    /**
     * 带光环厨师信息的菜谱
     */
    data class RecipeWithAuraChefs(
        val recipe: Recipe,
        val requiredAuraChefs: List<Chef> = emptyList(), // 该菜谱需要的光环厨师
        val canReachGodTier: Boolean = false, // 是否能达到神级
        val expectedRank: Int = 0, // 应用所选光环后预计达到的品级（0~5）
        val originalGaps: Map<String, Int> = emptyMap() // 未加光环时的神差值（基于NEXT等互动后）
    )

    /**
     * 光环厨师组合评估结果
     */
    data class AuraChefCombinationResult(
        val auraChefs: List<Chef>, // 光环厨师组合（最多2个）
        val recipesWithAura: List<RecipeWithAuraChefs>, // 前10名菜谱的光环计算结果
        val godTierRecipeCount: Int, // 能达到神级的菜谱数量
        val totalTime: Int, // 能达到神级的菜谱总时间
        val score: Double // 组合评分
    )

    /**
     * 神级检查结果数据类
     */
    data class GodTierCheckResult(
        val allGodTier: Boolean,       // 是否所有菜谱都达到神级
        val recipesOptimized: Boolean  // 是否进行了菜谱优化替换
    )
    
    data class OneClickQueryResult(
        val success: Boolean,
        val selectedChefs: List<Chef>, // 自动选择的厨师组合（3个）
        val selectedEquips: List<Equip>, // 自动选择的厨具组合（3个）
        val selectedRecipes: List<Recipe>, // 自动选择的菜谱组合（9个）
        val recipePortions: List<Int>, // 每个菜谱的实际分配份数（9个，对应selectedRecipes）
        val message: String // 结果描述信息
    )
    
    /**
     * 执行一键查询
     * @param targetChef 选择框中选择的未修炼厨师
     * @param gameData 游戏数据
     * @param allChefs 所有厨师数据（包含个人状态）
     * @param allRecipes 所有菜谱数据（包含个人状态）
     * @param allEquips 所有厨具数据（包含个人状态）
     * @param skills 技能数据
     * @param ultimateSkills 个人技法状态
     * @param recipeLimits 个人菜谱上限
     * @return 查询结果
     */
    fun executeOneClickQuery(
        targetChef: Chef,
        gameData: GameData,
        allChefs: List<Chef>,
        allRecipes: List<Recipe>,
        allEquips: List<Equip>,
        skills: List<Skill>,
        ultimateSkills: UltimateSkillsState,
        recipeLimits: RecipeLimitsState,
        settingsStorage: com.example.show_auto.data.SettingsStorage
    ): OneClickQueryResult {
        
        
        // 测试日志：检查目标厨师的基本信息

        // 获取设置页面中选中的光环厨师
        val enabledAuraChefs = settingsStorage.getSelectedAuraChefs()
        currentEnabledAuraChefs = enabledAuraChefs
        
        // 获取修炼任务
        var quest = getFirstUltimateQuest(targetChef, gameData.quests)
        
        // 如果没有找到任务，创建一个默认任务用于测试
        if (quest == null) {
            quest = createDefaultQuest(targetChef)
        }
        
        if (quest == null) {
            return OneClickQueryResult(
                success = false,
                selectedChefs = emptyList(),
                selectedEquips = emptyList(),
                selectedRecipes = emptyList(),
                recipePortions = emptyList(),
                message = "未找到${targetChef.name}的修炼任务"
            )
        }
        
        // 获取任务条件
        val condition = quest.conditions.firstOrNull()
        if (condition == null) {
            return OneClickQueryResult(
                success = false,
                selectedChefs = emptyList(),
                selectedEquips = emptyList(),
                selectedRecipes = emptyList(),
                recipePortions = emptyList(),
                message = "修炼任务条件为空"
            )
        }
        
        // 第1步：初始化厨师组合
        val initialChefs = initializeChefCombination(targetChef, allChefs, skills, enabledAuraChefs)
        
        // 确定未修炼厨师在组合中的位置
        val targetChefIndex = initialChefs.indexOfFirst { it.chefId == targetChef.chefId }
        if (targetChefIndex == -1) {
            return OneClickQueryResult(
                success = false,
                selectedChefs = emptyList(),
                selectedEquips = emptyList(),
                selectedRecipes = emptyList(),
                recipePortions = emptyList(),
                message = "未修炼厨师在组合中未找到"
            )
        }
        
        // 第2步：初始菜谱分配（只查询已有菜谱）
        var currentChefs = initialChefs.toMutableList()
        var currentEquips = mutableListOf<Equip>(Equip(), Equip(), Equip()) // 初始化空厨具
        
        val initialAllocation = allocateInitialRecipes(
            condition, 
            allRecipes.filter { it.got }, 
            currentChefs, // 传入完整的厨师组合
            currentEquips, // 传入完整的厨具组合
            targetChefIndex, // 传递厨师位置索引
            skills, 
            ultimateSkills,
            recipeLimits,
            allChefs // 传入完整的厨师列表
        )
        
        var currentRecipes = initialAllocation.recipes.toMutableList()
        var currentPortions = initialAllocation.portions.toMutableList()
        
        // 更新厨师组合（包含第二步分配的光环厨师）
        if (initialAllocation.updatedChefs.isNotEmpty()) {
            currentChefs = initialAllocation.updatedChefs.toMutableList()
        }
        
        // 检查第2步分配的菜谱是否都已达到神级
        val recipeLimitsList = listOf(recipeLimits.star1, recipeLimits.star2, recipeLimits.star3, recipeLimits.star4, recipeLimits.star5)
        val godTierResult = checkAllRecipesGodTier(currentRecipes, currentPortions, currentChefs, currentEquips, targetChefIndex, skills, ultimateSkills, enabledAuraChefs, allRecipes, condition, recipeLimitsList, settingsStorage)
        
        if (godTierResult.allGodTier && !godTierResult.recipesOptimized) {

            
            // 统一重新计算所有菜谱份数（确保准确性）
            val finalPortions = recalculateAllPortions(currentRecipes, currentChefs, recipeLimitsList, condition.num)
            
            // 保存星级筛选状态
            settingsStorage.setRecipeFilterForQuest(condition.rarity)
            
            val finalEquips = expandToThreeEquips(currentEquips)
            return OneClickQueryResult(
                success = true,
                selectedChefs = currentChefs,
                selectedEquips = finalEquips,
                selectedRecipes = currentRecipes,
                recipePortions = finalPortions, // 使用重新计算的份数
                message = "已为${targetChef.name}生成修炼任务组合（第2步完成）：${quest.goal}"
            )
        } else if (godTierResult.allGodTier && godTierResult.recipesOptimized) {
        }
        
        // 第4步：重新评估菜谱（跳过第3步，直接执行第4步）
        // 如果第2步已经进行了菜谱优化，则跳过重新分配
        if (!godTierResult.recipesOptimized) {
            currentRecipes = reevaluateRecipes(
                condition,
                allRecipes.filter { it.got },
                currentChefs,
                currentEquips,
                currentRecipes,
                targetChefIndex,
                skills,
                ultimateSkills,
                recipeLimits
            )
        } else {
        }
        
        // 第5步：厨具推荐补强（已有厨具）
        enhanceWithAvailableEquips(currentChefs, currentEquips, currentRecipes, allEquips, skills, allChefs, allRecipes, targetChefIndex, ultimateSkills, settingsStorage)
        
        // 第6步：最终菜谱优化（已有厨具后）
        // 如果第2步已经进行了菜谱优化，则跳过重新分配
        if (!godTierResult.recipesOptimized) {
            currentRecipes = reevaluateRecipes(
                condition,
                allRecipes.filter { it.got },
                currentChefs,
                currentEquips,
                currentRecipes,
                targetChefIndex,
                skills,
                ultimateSkills,
                recipeLimits
            )
        } else {
        }
        
        // 第7步：厨具推荐补强（任意厨具）
        enhanceWithAnyEquips(currentChefs, currentEquips, currentRecipes, allEquips, skills, allChefs, allRecipes, targetChefIndex, ultimateSkills, settingsStorage)
        
        // 第8步：兜底方案（未拥有菜谱）- 根据配置决定是否执行
        if (settingsStorage.getUseUnownedRecipes()) {
            val finalAllocation = reevaluateRecipesWithUnowned(
                condition,
                allRecipes, // 包括未拥有菜谱
                currentChefs,
                currentEquips,
                currentRecipes,
                currentPortions,
                targetChefIndex,
                skills,
                ultimateSkills,
                recipeLimits,
                settingsStorage // 传入settingsStorage以便持久化状态
            )
            currentRecipes = finalAllocation.recipes.toMutableList()
            currentPortions = finalAllocation.portions.toMutableList()
        }
        
        // 扩展厨具到3个
        val finalEquips = expandToThreeEquips(currentEquips)
        
        // 统一重新计算所有菜谱份数（确保准确性）
        val finalPortions = recalculateAllPortions(currentRecipes, currentChefs, recipeLimitsList, condition.num)
        
        // 保存星级筛选状态
        settingsStorage.setRecipeFilterForQuest(condition.rarity)
        
        
        return OneClickQueryResult(
            success = true,
            selectedChefs = currentChefs,
            selectedEquips = finalEquips,
            selectedRecipes = currentRecipes, // 已经是9个菜谱
            recipePortions = finalPortions, // 使用重新计算的份数
            message = "已为${targetChef.name}生成修炼任务组合：${quest.goal}"
        )
    }
    
    /**
     * 一键查询专用的厨具推荐计算函数
     * 使用与UI相同的逻辑
     */
    private fun calculateEquipRecommendationForOneClick(
        chef: Chef,
        recipes: List<Recipe>,
        allEquips: List<Equip>,
        skills: List<Skill>,
        allChefs: List<Chef>,
        allRecipes: List<Recipe>
    ): EquipRecommendationCalculator.RecommendationResult {
        // 转换为List<Recipe?>类型，因为EquipRecommendationCalculator期望的是可空类型
        val nullableRecipes: List<Recipe?> = recipes
        
        return EquipRecommendationCalculator.calculateRecommendation(
            chef = chef,
            recipes = nullableRecipes,
            allEquips = allEquips,
            skills = skills,
            ultimateSkills = UltimateSkillsState(), // 传递空的个人技法，因为已经应用到chef中了
            allChefs = allChefs,
            allRecipes = allRecipes
        )
    }
    
    /**
     * 检查所有分配的菜谱是否都达到神级，如果是则根据配置决定是否早期退出
     * 如果开启了"优先使用时间较短菜谱"，会尝试找到更短时间的可替换菜谱
     * 返回检查结果，包含是否达到神级和是否进行了优化
     */
    private fun checkAllRecipesGodTier(
        currentRecipes: MutableList<Recipe>,
        currentPortions: MutableList<Int>,
        currentChefs: List<Chef>,
        currentEquips: List<Equip>,
        targetChefIndex: Int,
        skills: List<Skill>,
        ultimateSkills: UltimateSkillsState,
        enabledAuraChefs: Set<String>,
        allRecipes: List<Recipe>,
        condition: QuestCondition,
        recipeLimits: List<Int>,
        settingsStorage: com.example.show_auto.data.SettingsStorage
    ): GodTierCheckResult {
        val targetChef = currentChefs.getOrNull(targetChefIndex) ?: return GodTierCheckResult(false, false)
        val targetEquip = currentEquips.getOrNull(targetChefIndex) ?: Equip()
        
        // 计算厨师间技法影响（使用设置页面的选择）
        val chefInteractions = ChefInteractionCalculator.calculateChefInteractions(currentChefs, skills, enabledAuraChefs)
        
        // 应用所有技法加成
        val enhancedChef = ChefSkillCalculator.applyAllSkills(
            chef = targetChef,
            ultimateSkills = ultimateSkills,
            equip = targetEquip,
            skills = skills,
            chefInteractionBonus = chefInteractions.getOrNull(targetChefIndex)
        )
        
        // 检查目标厨师的3个菜谱位置是否都达到神级
        val targetRecipes = mutableListOf<Recipe>()
        for (i in 0..2) {
            val recipeIndex = targetChefIndex * 3 + i
            if (recipeIndex >= currentRecipes.size) return GodTierCheckResult(false, false)
            
            val recipe = currentRecipes[recipeIndex]
            if (recipe.name.isEmpty()) return GodTierCheckResult(false, false) // 空菜谱不算达到神级
            
            val rank = RecipeRankCalculator.calculateRecipeRank(enhancedChef, recipe)
            if (rank < 4) { // 品级小于4（神级）
                return GodTierCheckResult(false, false)
            }
            targetRecipes.add(recipe)
        }
        
        
        // 如果没有开启"优先使用时间较短菜谱"，直接返回true
        val preferShorterTime = settingsStorage.getPreferShorterTimeRecipes()
        if (!preferShorterTime) {
            return GodTierCheckResult(true, false)
        }
        
        
        // 第一次筛选：找到可以通过厨具达到神级的已拥有菜谱，并且必须包含所需技法
        val usePowerfulEquips = settingsStorage.getUsePowerfulEquips()
        val candidateRecipes = allRecipes.filter { recipe ->
            recipe.got && // 已拥有
            recipe.rarity == condition.rarity && // 符合星级要求
            recipe.name.isNotEmpty() &&
            !targetRecipes.contains(recipe) && // 不是当前已分配的菜谱
            hasRequiredSkill(recipe, condition.skill) && // 必须包含所需技法
            canReachGodTierWithEquip(enhancedChef, recipe, usePowerfulEquips)
        }.sortedBy { it.time } // 按时间排序
        .take(10) // 只保留时间最短的10个菜谱
        
        candidateRecipes.forEach { recipe ->
            val gaps = calculateRecipeGodTierGaps(enhancedChef, recipe)
        }
        
        if (candidateRecipes.isEmpty()) {
            return GodTierCheckResult(true, false) // 没有候选菜谱，直接返回
        }
        
        // 如果只有一个候选菜谱，直接进行时间比较
        if (candidateRecipes.size == 1) {
            val candidate = candidateRecipes.first()
            val longestCurrentRecipe = targetRecipes.maxByOrNull { it.time }
            if (longestCurrentRecipe != null && candidate.time < longestCurrentRecipe.time) {
                replaceRecipeInAllocation(currentRecipes, currentPortions, targetChefIndex, longestCurrentRecipe, candidate, condition, recipeLimits)
                return GodTierCheckResult(true, true) // 进行了优化，继续后续步骤
            }
            return GodTierCheckResult(true, false)
        }
        
        // 第二次筛选：只保留单技法缺失的菜谱
        val singleGapRecipes = candidateRecipes.filter { recipe ->
            val gaps = calculateRecipeGodTierGaps(enhancedChef, recipe)
            gaps.size == 1
        }
        
        
        if (singleGapRecipes.isEmpty()) {
            return GodTierCheckResult(true, false)
        }
        
        if (singleGapRecipes.size == 1) {
            val candidate = singleGapRecipes.first()
            val longestCurrentRecipe = targetRecipes.maxByOrNull { it.time }
            if (longestCurrentRecipe != null && candidate.time < longestCurrentRecipe.time) {
                replaceRecipeInAllocation(currentRecipes, currentPortions, targetChefIndex, longestCurrentRecipe, candidate, condition, recipeLimits)
                return GodTierCheckResult(true, true)
            }
            return GodTierCheckResult(true, false)
        }
        
        // 第三次筛选：以时间最短菜谱的缺失技法为准
        val shortestRecipe = singleGapRecipes.minByOrNull { it.time }
        if (shortestRecipe == null) return GodTierCheckResult(true, false)
        
        val shortestGaps = calculateRecipeGodTierGaps(enhancedChef, shortestRecipe)
        val targetSkillType = shortestGaps.keys.first()
        
        val finalCandidates = singleGapRecipes.filter { recipe ->
            val gaps = calculateRecipeGodTierGaps(enhancedChef, recipe)
            gaps.containsKey(targetSkillType)
        }
        
        
        // 将最终候选菜谱与当前神级菜谱合并，重新排序取前三
        val allCandidates = (targetRecipes + finalCandidates).sortedBy { it.time }
        val newTopThree = allCandidates.take(3)
        
        // 检查是否有变化
        if (newTopThree != targetRecipes) {
            
            // 重新分配这三个菜谱（只更新菜谱，份数稍后统一计算）
            for (i in 0..2) {
                val recipeIndex = targetChefIndex * 3 + i
                if (recipeIndex < currentRecipes.size && i < newTopThree.size) {
                    currentRecipes[recipeIndex] = newTopThree[i]
                }
            }
            return GodTierCheckResult(true, true) // 进行了优化，继续后续步骤
        }
        
        return GodTierCheckResult(true, false) // 没有更好的组合，直接返回
    }
    
    /**
     * 在分配中替换菜谱
     */
    private fun replaceRecipeInAllocation(
        currentRecipes: MutableList<Recipe>,
        currentPortions: MutableList<Int>,
        targetChefIndex: Int,
        oldRecipe: Recipe,
        newRecipe: Recipe,
        condition: QuestCondition,
        recipeLimits: List<Int>
    ) {
        // 找到要替换的菜谱位置（只更新菜谱，份数稍后统一计算）
        for (i in 0..2) {
            val recipeIndex = targetChefIndex * 3 + i
            if (recipeIndex < currentRecipes.size && currentRecipes[recipeIndex] == oldRecipe) {
                currentRecipes[recipeIndex] = newRecipe
                break
            }
        }
    }
    
    /**
     * 获取厨师的第一个修炼任务
     */
    private fun getFirstUltimateQuest(chef: Chef, quests: List<Quest>): Quest? {
        if (chef.ultimateGoal.isEmpty()) return null
        val questId = chef.ultimateGoal.first()
        return quests.find { it.questId == questId }
    }
    
    /**
     * 为厨师创建默认测试任务
     */
    private fun createDefaultQuest(chef: Chef): Quest? {
        // 根据厨师的主要技法创建默认任务
        val mainSkill = getChefMainSkill(chef)
        
        return Quest(
            questId = 9999,
            goal = "测试任务：制作${mainSkill}技法二星神级料理60份",
            conditions = listOf(
                QuestCondition(
                    skill = mainSkill,
                    rarity = 2,
                    rank = 4, // 神级
                    num = 60
                )
            )
        )
    }
    
    /**
     * 获取厨师的主要技法
     */
    private fun getChefMainSkill(chef: Chef): String {
        val skills = mapOf(
            "stirfry" to chef.stirfry,
            "boil" to chef.boil,
            "knife" to chef.knife,
            "fry" to chef.fry,
            "bake" to chef.bake,
            "steam" to chef.steam
        )
        
        return skills.maxByOrNull { it.value }?.key ?: "stirfry"
    }
    
    /**
     * 第1步：初始化厨师组合
     */
    private fun initializeChefCombination(targetChef: Chef, allChefs: List<Chef>, skills: List<Skill>, enabledAuraChefs: Set<String>): List<Chef> {
        val chefs = mutableListOf<Chef>()

        // 查找在设置中选中的NEXT类型技能厨师（包括未拥有的厨师）
        val nextChefs = allChefs.filter { chef ->
            enabledAuraChefs.contains(chef.name) && hasNextTypeSkill(chef, skills)
        }.sortedByDescending { chef ->
            calculateTotalSkillValue(chef)
        }
        
        if (nextChefs.isNotEmpty()) {
            chefs.add(nextChefs.first()) // 技法加成最高的NEXT厨师放第1位
            chefs.add(targetChef) // 未修炼厨师放第2位
        } else {
            chefs.add(targetChef) // 未修炼厨师放第1位
        }
        
        // 补齐到3个厨师
        while (chefs.size < 3) {
            chefs.add(Chef()) // 空厨师
        }
        
        return chefs
    }
    
    /**
     * 检查厨师是否有NEXT类型技能
     */
    private fun hasNextTypeSkill(chef: Chef, skills: List<Skill>): Boolean {
        if (!chef.hasUltimateSkill()) return false

        return chef.getAllUltimateSkills().any { sid ->
            val ultimateSkill = skills.find { it.skillId == sid } ?: return@any false
            val effects = ChefInteractionCalculator.parseSkillDescription(ultimateSkill.desc)
            effects.any { it.condition == ChefInteractionCalculator.SkillCondition.NEXT }
        }
    }
    
    /**
     * 检查厨师是否有PARTIAL类型技能
     */
    private fun hasPartialTypeSkill(chef: Chef, skills: List<Skill>): Boolean {
        if (!chef.hasUltimateSkill()) return false

        return chef.getAllUltimateSkills().any { sid ->
            val ultimateSkill = skills.find { it.skillId == sid } ?: return@any false
            val effects = ChefInteractionCalculator.parseSkillDescription(ultimateSkill.desc)
            effects.any { it.condition == ChefInteractionCalculator.SkillCondition.PARTIAL }
        }
    }
    
    /**
     * 计算厨师的总技法值
     */
    private fun calculateTotalSkillValue(chef: Chef): Int {
        return chef.stirfry + chef.boil + chef.knife + chef.fry + chef.bake + chef.steam
    }
    
    /**
     * 直接复用RecipeCalculatorPage的菜谱查询逻辑
     */
    private fun queryRecipesWithInterface(
        condition: QuestCondition,
        allRecipes: List<Recipe>,
        selectedRecipes: List<Recipe>,
        currentChefs: List<Chef>,
        currentEquips: List<Equip>,
        targetChefIndex: Int,
        skills: List<Skill>,
        ultimateSkills: UltimateSkillsState,
        onlyShowOwned: Boolean = true
    ): List<Recipe> {
        
        
        // 设置星级筛选参数（根据修炼任务要求）
        val filterRarity1 = condition.rarity == 1
        val filterRarity2 = condition.rarity == 2
        val filterRarity3 = condition.rarity == 3
        val filterRarity4 = condition.rarity == 4
        val filterRarity5 = condition.rarity == 5
        
        // 计算厨师间技法影响（使用设置页面的选择）
        val chefInteractions = ChefInteractionCalculator.calculateChefInteractions(currentChefs, skills, currentEnabledAuraChefs)
        val targetChef = currentChefs.getOrNull(targetChefIndex) ?: Chef()
        val targetEquip = currentEquips.getOrNull(targetChefIndex) ?: Equip()
        
        
        // 直接复用RecipeCalculatorPage的逻辑，只添加技法筛选
        val baseFiltered = allRecipes.filter { recipe ->
            // 基础筛选（与RecipeCalculatorPage完全相同）
            val basicFilter = (!onlyShowOwned || recipe.got) && 
                !selectedRecipes.contains(recipe)
            
            if (!basicFilter) return@filter false
            
            // 星级筛选（与RecipeCalculatorPage完全相同）
            val rarityFilter = when {
                filterRarity1 && recipe.rarity == 1 -> true
                filterRarity2 && recipe.rarity == 2 -> true
                filterRarity3 && recipe.rarity == 3 -> true
                filterRarity4 && recipe.rarity == 4 -> true
                filterRarity5 && recipe.rarity == 5 -> true
                !filterRarity1 && !filterRarity2 && !filterRarity3 && !filterRarity4 && !filterRarity5 -> true
                else -> false
            }
            
            // 添加技法筛选（一键查询特有）
            val skillFilter = hasRequiredSkill(recipe, condition.skill)
            
            rarityFilter && skillFilter
        }
        
        
        // 应用技法加成（使用当前的厨师组合和厨师间互动）
        val enhancedChef = ChefSkillCalculator.applyAllSkills(
            targetChef, ultimateSkills, targetEquip, skills, chefInteractions.getOrNull(targetChefIndex)
        )
        
        // 排序（使用新逻辑：神级传级混合按时间排序，特级及以下按品级+神差值+时间排序）
        val sortedRecipes = baseFiltered.sortedWith { recipe1, recipe2 ->
            val rank1 = RecipeRankCalculator.calculateRecipeRank(enhancedChef, recipe1)
            val rank2 = RecipeRankCalculator.calculateRecipeRank(enhancedChef, recipe2)
            
            // 检查是否为神级或传级
            val isHighTier1 = rank1 >= 4 // 神级(4)或传级(5)
            val isHighTier2 = rank2 >= 4
            
            when {
                // 如果都是神/传级，按时间排序（可以混合）
                isHighTier1 && isHighTier2 -> recipe1.time.compareTo(recipe2.time)
                // 如果一个是神/传级，另一个不是，优先神/传级
                isHighTier1 && !isHighTier2 -> -1
                !isHighTier1 && isHighTier2 -> 1
                // 如果都不是神/传级（特级及以下），使用新的排序逻辑
                else -> {
                    val rankComparison = rank2.compareTo(rank1) // 品级高到低
                    if (rankComparison != 0) {
                        rankComparison
                    } else {
                        // 品级相同时，使用神差值排序逻辑
                        compareByGodTierGaps(enhancedChef, recipe1, recipe2)
                    }
                }
            }
        }
        
        
        return sortedRecipes
    }
    
    /**
     * 第2步：智能菜谱分配（带光环厨师组合优化）
     */
    private fun allocateInitialRecipes(
        condition: QuestCondition,
        availableRecipes: List<Recipe>,
        currentChefs: List<Chef>,
        currentEquips: List<Equip>,
        targetChefIndex: Int,
        skills: List<Skill>,
        ultimateSkills: UltimateSkillsState,
        recipeLimits: RecipeLimitsState,
        allChefs: List<Chef> // 新增参数：完整的厨师列表
    ): RecipeAllocation {
        
        // 调用菜谱查询接口获取前10名菜谱
        val sortedRecipes = queryRecipesWithInterface(
            condition = condition,
            allRecipes = availableRecipes,
            selectedRecipes = emptyList(),
            currentChefs = currentChefs,
            currentEquips = currentEquips,
            targetChefIndex = targetChefIndex,
            skills = skills,
            ultimateSkills = ultimateSkills,
            onlyShowOwned = true
        ).take(10) // 只取前10名菜谱
        
        
        // 如果查询结果为空，使用一些默认菜谱进行测试
        val finalSortedRecipes = if (sortedRecipes.isEmpty()) {
            availableRecipes.filter { it.got && it.rarity == condition.rarity }.take(10)
        } else {
            sortedRecipes
        }
        
        
        // 获取目标厨师和厨具
        val targetChef = currentChefs.getOrNull(targetChefIndex) ?: Chef()
        val targetEquip = currentEquips.getOrNull(targetChefIndex) ?: Equip()
        
        // 计算可用空位数量（需要检查第一步是否分配了NEXT厨师）
        val hasNextChef = currentChefs.any { chef ->
            chef.chefId != targetChef.chefId && chef.name.isNotEmpty() && hasNextTypeSkill(chef, skills)
        }
        val availableSlots = if (hasNextChef) {
            1 // 如果有NEXT厨师，只剩1个空位
        } else {
            2 // 如果没有NEXT厨师，有2个空位
        }
        val maxAuraChefs = availableSlots
        
        // 获取所有可用的光环厨师
        val availableAuraChefs = currentEnabledAuraChefs.mapNotNull { chefName ->
            val found = allChefs.find { it.name == chefName }
            found
        }.distinct()
        
        
        // 生成所有可能的光环厨师组合并评估
        val bestCombination = findBestAuraChefCombination(
            recipes = finalSortedRecipes,
            targetChef = targetChef,
            targetEquip = targetEquip,
            availableAuraChefs = availableAuraChefs,
            maxAuraChefs = maxAuraChefs,
            skills = skills,
            ultimateSkills = ultimateSkills,
            condition = condition,
            initialChefs = currentChefs // 传入当前的厨师组合（包含第一步分配的NEXT厨师）
        )
        
        
        // 根据最优组合选择3道菜谱
        val selectedRecipesWithAura = selectOptimalRecipeCombination(
            combinationResult = bestCombination,
            recipeLimits = recipeLimits,
            condition = condition
        )
        
        
        // 更新厨师组合（将选中的光环厨师加入到空位）
        val updatedChefs = currentChefs.toMutableList()
        var auraChefIndex = 0
        for (slotIndex in 0 until updatedChefs.size) {
            if (auraChefIndex >= bestCombination.auraChefs.size) break
            
            // 找到空位（厨师名为空的位置）
            if (updatedChefs[slotIndex].name.isEmpty()) {
                updatedChefs[slotIndex] = bestCombination.auraChefs[auraChefIndex]
                auraChefIndex++
            }
        }
        
        // 计算菜谱份数
        val allocatedPortions = mutableListOf<Int>()
        var remainingPortions = condition.num
        
        selectedRecipesWithAura.forEach { recipeWithAura ->
            val maxPortions = calculateMaxPortions(recipeWithAura.recipe, recipeLimits)
            val actualAllocated = minOf(maxPortions, remainingPortions)
            allocatedPortions.add(actualAllocated)
            remainingPortions -= actualAllocated
        }
        
        // 创建9个菜谱的数组，将选中的菜谱放到目标厨师对应的位置
        val fullRecipeList = mutableListOf<Recipe>()
        val fullPortionsList = mutableListOf<Int>()
        repeat(9) { 
            fullRecipeList.add(Recipe())
            fullPortionsList.add(0)
        }
        
        // 存储菜谱光环厨师信息到全局变量
        val recipeAuraMap = mutableMapOf<Recipe, List<Chef>>()
        selectedRecipesWithAura.forEach { recipeWithAura ->
            recipeAuraMap[recipeWithAura.recipe] = recipeWithAura.requiredAuraChefs
        }
        currentRecipeAuraChefs = recipeAuraMap
        
        // 将选中的菜谱和份数分配到目标厨师对应的位置
        selectedRecipesWithAura.forEachIndexed { index, recipeWithAura ->
            val recipeIndex = targetChefIndex * 3 + index
            if (recipeIndex < 9) {
                fullRecipeList[recipeIndex] = recipeWithAura.recipe
                fullPortionsList[recipeIndex] = allocatedPortions.getOrElse(index) { 0 }
            }
        }
        

        
        return RecipeAllocation(fullRecipeList, fullPortionsList, updatedChefs)
    }
    
    /**
     * 查找最佳光环厨师组合（新逻辑：按技法分组，智能组合）
     */
    private fun findBestAuraChefCombination(
        recipes: List<Recipe>,
        targetChef: Chef,
        targetEquip: Equip,
        availableAuraChefs: List<Chef>,
        maxAuraChefs: Int,
        skills: List<Skill>,
        ultimateSkills: UltimateSkillsState,
        condition: QuestCondition,
        initialChefs: List<Chef> // 新增：第一步的厨师组合
    ): AuraChefCombinationResult {
        
        // 1. 按技法分组光环厨师
        val skillGroupedChefs = groupAuraChefsBySkill(availableAuraChefs, skills)
        
        // 2. 每组保留技法值最高的前maxAuraChefs个厨师
        val topChefsPerSkill = skillGroupedChefs.mapValues { (skillType, chefs) ->
            chefs.sortedByDescending { chef ->
                calculateChefSkillBonus(chef, skillType, skills)
            }.take(maxAuraChefs)
        }
        
        // 3. 生成所有可能的厨师组合（排除已存在的NEXT厨师）
        val nextChef = initialChefs.find { chef -> 
            chef.chefId != targetChef.chefId && chef.name.isNotEmpty() && hasNextTypeSkill(chef, skills) 
        }
        val filteredTopChefsPerSkill = if (nextChef != null) {
            // 如果有NEXT厨师，从可选光环厨师中排除它
            topChefsPerSkill.mapValues { (_, chefs) ->
                chefs.filter { it.chefId != nextChef.chefId }
            }
        } else {
            topChefsPerSkill
        }
        val allCombinations = generateSmartChefCombinations(filteredTopChefsPerSkill, maxAuraChefs)
        
        // 4. 评估每个组合
        var bestResult = AuraChefCombinationResult(
            auraChefs = emptyList(),
            recipesWithAura = emptyList(),
            godTierRecipeCount = 0,
            totalTime = Int.MAX_VALUE,
            score = Double.NEGATIVE_INFINITY // 使用负无穷大，确保任何实际评分都比它大
        )
        
        for (combination in allCombinations) {
            val result = evaluateAuraChefCombinationNew(
                targetChef = targetChef,
                targetEquip = targetEquip,
                auraChefs = combination,
                skills = skills,
                ultimateSkills = ultimateSkills,
                condition = condition,
                initialChefs = initialChefs,
                availableRecipes = recipes
            )
            
            // 使用新的评分标准：神差值总和越小越好
            if (result.score > bestResult.score) {
                bestResult = result
            }
        }
        
        return bestResult
    }
    
    /**
     * 生成指定数量的厨师组合
     */
    private fun generateCombinations(chefs: List<Chef>, count: Int): List<List<Chef>> {
        if (count == 0) return listOf(emptyList())
        if (count > chefs.size) return emptyList()
        if (count == chefs.size) return listOf(chefs)
        
        val result = mutableListOf<List<Chef>>()
        
        fun backtrack(start: Int, current: MutableList<Chef>) {
            if (current.size == count) {
                result.add(current.toList())
                return
            }
            
            for (i in start until chefs.size) {
                current.add(chefs[i])
                backtrack(i + 1, current)
                current.removeAt(current.size - 1)
            }
        }
        
        backtrack(0, mutableListOf())
        return result
    }
    
    /**
     * 评估光环厨师组合
     */
    private fun evaluateAuraChefCombination(
        recipes: List<Recipe>,
        targetChef: Chef,
        targetEquip: Equip,
        auraChefs: List<Chef>,
        skills: List<Skill>,
        ultimateSkills: UltimateSkillsState,
        condition: QuestCondition,
        initialChefs: List<Chef> // 新增：第一步的厨师组合
    ): AuraChefCombinationResult {
        
        
        // 构建完整厨师组合用于计算技法交互
        // 需要考虑第一步分配的NEXT厨师和当前的光环厨师组合
        val fullChefCombination = mutableListOf<Chef>().apply {
            // 从第一步的厨师组合开始
            addAll(initialChefs)
            
            // 替换光环厨师位置（保持NEXT厨师不变）
            auraChefs.forEachIndexed { index, auraChef ->
                val slotIndex = if (initialChefs[0].chefId == targetChef.chefId) {
                    // 如果目标厨师在第0位，光环厨师放在1、2位
                    index + 1
                } else {
                    // 如果目标厨师在第1位，光环厨师放在0、2位
                    if (index == 0) 0 else 2
                }
                if (slotIndex < size) {
                    set(slotIndex, auraChef)
                }
            }
        }
        
        // 计算厨师间技法影响（包括第一步的NEXT厨师）
        val chefInteractions = ChefInteractionCalculator.calculateChefInteractions(fullChefCombination, skills, currentEnabledAuraChefs)
        
        // 应用所有技法加成到目标厨师（包括NEXT厨师的加成）
        val enhancedChef = ChefSkillCalculator.applyAllSkills(
            chef = targetChef,
            ultimateSkills = ultimateSkills,
            equip = targetEquip,
            skills = skills,
            chefInteractionBonus = chefInteractions.getOrNull(if (initialChefs[0].chefId == targetChef.chefId) 0 else 1) // 目标厨师的实际位置
        )
        
        // 计算每个菜谱在该光环组合下的表现
        val recipesWithAura = recipes.map { recipe ->
            // 计算当前组合下的实际品级（已包含NEXT/PARTIAL等加成）
            val rankAfter = RecipeRankCalculator.calculateRecipeRank(enhancedChef, recipe)
            var canReachGodTier = rankAfter >= 4
            val requiredAuraChefs = mutableListOf<Chef>()
            // 仅当未达神级时才计算神差值
            val gaps = if (!canReachGodTier) calculateRecipeGodTierGaps(enhancedChef, recipe) else emptyMap()
            
            if (!canReachGodTier && gaps.isNotEmpty()) {
                // 尝试用光环厨师补齐缺陷
                val remainingGaps = gaps.toMutableMap()
                val usedAuraChefs = mutableSetOf<Chef>()
                
                // 优先处理缺陷最大的技法
                val sortedGaps = remainingGaps.entries.sortedByDescending { it.value }
                
                for ((skillType, gapValue) in sortedGaps) {
                    var remainingGap = gapValue
                    
                    // 查找能提供该技法的光环厨师
                    val suitableAuraChefs = auraChefs.filter { chef ->
                        !usedAuraChefs.contains(chef) && 
                        calculateChefSkillBonus(chef, skillType, skills) > 0
                    }.sortedByDescending { chef ->
                        calculateChefSkillBonus(chef, skillType, skills)
                    }
                    
                    
                    for (auraChef in suitableAuraChefs) {
                        val bonus = calculateChefSkillBonus(auraChef, skillType, skills)
                        if (bonus > 0) {
                            requiredAuraChefs.add(auraChef)
                            usedAuraChefs.add(auraChef)
                            remainingGap -= bonus
                            
                            if (remainingGap <= 0) break
                        }
                    }
                    
                    remainingGaps[skillType] = maxOf(0, remainingGap)
                }
                
                // 检查是否所有缺陷都被补齐
                canReachGodTier = remainingGaps.values.all { it <= 0 }
            }
            
            RecipeWithAuraChefs(
                recipe = recipe,
                requiredAuraChefs = requiredAuraChefs,
                canReachGodTier = canReachGodTier,
                expectedRank = if (canReachGodTier) 4 else RecipeRankCalculator.calculateRecipeRank(enhancedChef, recipe),
                originalGaps = gaps
            )
        }
        
        
        // 统计神级菜谱
        val godTierRecipes = recipesWithAura.filter { it.canReachGodTier }
        val godTierRecipeCount = godTierRecipes.size
        val totalTime = godTierRecipes.sumOf { it.recipe.time }
        
        // 计算技法覆盖度
        val skillTypes = setOf("炒", "煮", "切", "炸", "烤", "蒸")
        val coveredSkills = auraChefs.flatMap { chef ->
            skillTypes.filter { skillType ->
                calculateChefSkillBonus(chef, skillType, skills) > 0
            }
        }.distinct().size
        
        // 计算同类型神差值统计
        val skillGapStats = calculateSkillGapStatistics(recipesWithAura, targetChef, targetEquip, skills, ultimateSkills)
        
        // 计算评分
        val score = calculateCombinationScore(godTierRecipeCount, totalTime, skillGapStats)
        
        return AuraChefCombinationResult(
            auraChefs = auraChefs,
            recipesWithAura = recipesWithAura,
            godTierRecipeCount = godTierRecipeCount,
            totalTime = totalTime,
            score = score
        )
    }
    
    /**
     * 神差值统计信息
     */
    data class SkillGapStats(
        val singleGapRecipeCount: Int, // 只有单类型神差值的菜谱数量
        val multiGapRecipeCount: Int,  // 多类型神差值的菜谱数量
        val totalGapValue: Int,        // 总神差值
        val skillTypeCount: Int        // 涉及的神差值类型数量
    )
    
    /**
     * 计算神差值统计
     */
    private fun calculateSkillGapStatistics(
        recipesWithAura: List<RecipeWithAuraChefs>,
        targetChef: Chef,
        targetEquip: Equip,
        skills: List<Skill>,
        ultimateSkills: UltimateSkillsState
    ): SkillGapStats {
        val godTierRecipes = recipesWithAura.filter { it.canReachGodTier }
        
        var singleGapCount = 0
        var multiGapCount = 0
        var totalGapValue = 0
        val skillTypes = mutableSetOf<String>()
        
        godTierRecipes.forEach { recipeWithAura ->
            // 计算该菜谱在没有光环厨师时的神差值
            val gaps = calculateRecipeGodTierGaps(targetChef, recipeWithAura.recipe)
            
            if (gaps.isNotEmpty()) {
                totalGapValue += gaps.values.sum()
                skillTypes.addAll(gaps.keys)
                
                if (gaps.size == 1) {
                    singleGapCount++
                } else {
                    multiGapCount++
                }
            }
        }
        
        return SkillGapStats(
            singleGapRecipeCount = singleGapCount,
            multiGapRecipeCount = multiGapCount,
            totalGapValue = totalGapValue,
            skillTypeCount = skillTypes.size
        )
    }
    
    /**
     * 计算组合评分
     */
    private fun calculateCombinationScore(godTierCount: Int, totalTime: Int, skillGapStats: SkillGapStats): Double {
        if (godTierCount == 0) return -1.0
        
        // 评分公式：
        // 1. 神级数量 × 10000（最高优先级）
        // 2. 单类型神差值菜谱数量 × 1000（优先单类型）
        // 3. 神差值类型数量 × -100（优先同类神差值）
        // 4. 总神差值 × -1（优先神差值小的）
        // 5. 总时间 × -0.1（最后按时间排序）
        return godTierCount * 10000.0 + 
               skillGapStats.singleGapRecipeCount * 1000.0 + 
               skillGapStats.skillTypeCount * -100.0 + 
               skillGapStats.totalGapValue * -1.0 + 
               totalTime * -0.1
    }
    
    /**
     * 选择最优菜谱组合
     */
    private fun selectOptimalRecipeCombination(
        combinationResult: AuraChefCombinationResult,
        recipeLimits: RecipeLimitsState,
        condition: QuestCondition
    ): List<RecipeWithAuraChefs> {
        
        
        val recipesWithAura = combinationResult.recipesWithAura
        val maxAuraChefs = 2 // 最多2个光环厨师
        
        // 生成所有可能的3菜谱组合
        val validCombinations = mutableListOf<List<RecipeWithAuraChefs>>()
        
        for (i in recipesWithAura.indices) {
            for (j in i + 1 until recipesWithAura.size) {
                for (k in j + 1 until recipesWithAura.size) {
                    val combination = listOf(recipesWithAura[i], recipesWithAura[j], recipesWithAura[k])
                    
                    // 检查该组合所需的光环厨师是否不超过限制
                    val requiredAuraChefs = combination.flatMap { it.requiredAuraChefs }.distinct()
                    if (requiredAuraChefs.size <= maxAuraChefs) {
                        validCombinations.add(combination)
                    }
                }
            }
        }
        
        if (validCombinations.isEmpty()) {
            // 如果没有可行组合，选择前3个菜谱（即使不满足约束）
            return recipesWithAura.take(3)
        }
        
        
        // 在可行组合中选择最优的
        val bestCombination = validCombinations.maxByOrNull { combination ->
            val godTierCount = combination.count { it.canReachGodTier }
            val totalTime = combination.sumOf { it.recipe.time }
            val noAuraCount = combination.count { it.requiredAuraChefs.isEmpty() }
            
            // 新的评分逻辑：优先品级，然后按您的规则
            // 1. 神级数量（最高优先级）
            // 2. 平均品级（传级>神级>特级>优级>可）
            // 3. 无光环菜谱数量
            // 4. 总时间（越短越好）
            val avgRank = combination.map { it.expectedRank }.average()
            val rankScore = avgRank * 10000 // 品级权重最高
            
            godTierCount * 100000 + rankScore + noAuraCount * 1000 - totalTime
        }
        
        
        val finalSelection = bestCombination ?: recipesWithAura.take(3)
        
        return finalSelection
    }
    
    /**
     * 检查菜谱是否包含所需技法
     */
    private fun hasRequiredSkill(recipe: Recipe, skillType: String): Boolean {
        return when (skillType.lowercase()) {
            "knife" -> recipe.knife > 0
            "stirfry" -> recipe.stirfry > 0
            "boil" -> recipe.boil > 0
            "fry" -> recipe.fry > 0
            "bake" -> recipe.bake > 0
            "steam" -> recipe.steam > 0
            else -> false
        }
    }
    
    /**
     * 按技法分组光环厨师
     */
    private fun groupAuraChefsBySkill(availableAuraChefs: List<Chef>, skills: List<Skill>): Map<String, List<Chef>> {
        val skillTypes = listOf("炒", "煮", "切", "炸", "烤", "蒸")
        val groupedChefs = mutableMapOf<String, MutableList<Chef>>()
        
        // 初始化分组
        skillTypes.forEach { skillType ->
            groupedChefs[skillType] = mutableListOf()
        }
        
        // 遍历所有光环厨师，按技法分组
        availableAuraChefs.forEach { chef ->
            skillTypes.forEach { skillType ->
                val skillBonus = calculateChefSkillBonus(chef, skillType, skills)
                if (skillBonus > 0) {
                    groupedChefs[skillType]?.add(chef)
                }
            }
        }
        
        return groupedChefs
    }
    
    /**
     * 生成智能厨师组合
     */
    private fun generateSmartChefCombinations(
        topChefsPerSkill: Map<String, List<Chef>>,
        maxAuraChefs: Int
    ): List<List<Chef>> {
        val allCombinations = mutableListOf<List<Chef>>()
        
        // 收集所有候选厨师（去重）
        val allCandidateChefs = topChefsPerSkill.values.flatten().distinct()
        
        // 根据空位数量决定生成哪些组合
        val targetCombinationSizes = when (maxAuraChefs) {
            2 -> {
                // 有两个空位时，优先生成两个厨师的组合，但如果厨师不足，也生成单厨师组合
                val availableSizes = mutableListOf<Int>()
                if (allCandidateChefs.size >= 2) availableSizes.add(2)
                if (allCandidateChefs.size >= 1) availableSizes.add(1)
                availableSizes.ifEmpty { listOf(0) } // 如果没有厨师，至少生成空组合
            }
            1 -> listOf(1) // 有一个空位时，只生成单厨师组合（必须填满空位）
            else -> (0..minOf(maxAuraChefs, allCandidateChefs.size)).toList() // 其他情况保持原逻辑
        }
        
        // 生成指定数量的厨师组合
        for (numChefs in targetCombinationSizes) {
            if (numChefs <= allCandidateChefs.size) {
                val combinations = generateCombinations(allCandidateChefs, numChefs)
                allCombinations.addAll(combinations)
            }
        }
        
        return allCombinations
    }
    
    /**
     * 新的光环厨师组合评估方法
     */
    private fun evaluateAuraChefCombinationNew(
        targetChef: Chef,
        targetEquip: Equip,
        auraChefs: List<Chef>,
        skills: List<Skill>,
        ultimateSkills: UltimateSkillsState,
        condition: QuestCondition,
        initialChefs: List<Chef>,
        availableRecipes: List<Recipe>
    ): AuraChefCombinationResult {
        
        // 构建完整厨师组合
        val fullChefCombination = mutableListOf<Chef>().apply {
            addAll(initialChefs)
            
            // 将光环厨师放入空位（不替换已有的NEXT厨师和目标厨师）
            var auraChefIndex = 0
            for (slotIndex in 0 until size) {
                if (auraChefIndex >= auraChefs.size) break
                
                // 找到空位（厨师名为空的位置）
                if (get(slotIndex).name.isEmpty()) {
                    set(slotIndex, auraChefs[auraChefIndex])
                    auraChefIndex++
                }
            }
        }
        

        
        // 计算厨师间技法影响
        // 传入光环厨师设置，确保光环厨师和NEXT厨师都能提供技法影响
        val chefInteractions = ChefInteractionCalculator.calculateChefInteractions(fullChefCombination, skills, currentEnabledAuraChefs)
        
        val targetChefIndex = if (initialChefs[0].chefId == targetChef.chefId) 0 else 1
        val interactionBonus = chefInteractions.getOrNull(targetChefIndex)
        
        // 应用所有技法加成到目标厨师
        val enhancedChef = ChefSkillCalculator.applyAllSkills(
            chef = targetChef,
            ultimateSkills = ultimateSkills,
            equip = targetEquip,
            skills = skills,
            chefInteractionBonus = interactionBonus
        )
        
        // 调用菜谱查询接口获取排序后的菜谱
        val sortedRecipes = queryRecipesWithInterface(
            condition = condition,
            allRecipes = availableRecipes,
            selectedRecipes = emptyList(),
            currentChefs = fullChefCombination,
            currentEquips = listOf(targetEquip, Equip(), Equip()),
            targetChefIndex = if (initialChefs[0].chefId == targetChef.chefId) 0 else 1,
            skills = skills,
            ultimateSkills = ultimateSkills,
            onlyShowOwned = true
        ).take(3) // 只取前3名菜谱
        
        // 计算神差值总和和神级菜谱数量
        var godTierCount = 0
        var totalGodTierGaps = 0
        var minGodTierGap = Int.MAX_VALUE
        
        sortedRecipes.forEach { recipe ->
            val rank = RecipeRankCalculator.calculateRecipeRank(enhancedChef, recipe)
            if (rank >= 4) {
                godTierCount++
            } else {
                val gaps = calculateRecipeGodTierGaps(enhancedChef, recipe)
                val gapValue = if (gaps.size == 1) {
                    gaps.values.first()
                } else {
                    gaps.values.maxOrNull() ?: 0 // 多神差值菜谱取最大值
                }
                totalGodTierGaps += gapValue
                minGodTierGap = minOf(minGodTierGap, gapValue)
            }
        }
        
        // 计算评分：优先神级数量，然后是神差值总和（越小越好），最后是最小神差值（越小越好）
        val score = godTierCount * 100000.0 - totalGodTierGaps * 100.0 - (if (minGodTierGap == Int.MAX_VALUE) 0 else minGodTierGap)
        

        
        val recipesWithAura = sortedRecipes.map { recipe ->
            val rank = RecipeRankCalculator.calculateRecipeRank(enhancedChef, recipe)
            RecipeWithAuraChefs(
                recipe = recipe,
                requiredAuraChefs = auraChefs,
                canReachGodTier = rank >= 4,
                expectedRank = rank,
                originalGaps = if (rank < 4) calculateRecipeGodTierGaps(enhancedChef, recipe) else emptyMap()
            )
        }
        
        return AuraChefCombinationResult(
            auraChefs = auraChefs,
            recipesWithAura = recipesWithAura,
            godTierRecipeCount = godTierCount,
            totalTime = sortedRecipes.sumOf { it.time },
            score = score
        )
    }
    
    /**
     * 根据神差值比较两个菜谱的排序
     * 排序规则：
     * 1. 优先展示只有单技法神差值的菜谱，按照神差值由低到高排序
     * 2. 多技法神差值的菜谱放在当前品级最后展示，按照每个菜谱神差值最低的那个技法升序排序
     * 3. 最后才按照时间排序
     */
    private fun compareByGodTierGaps(chef: Chef, recipe1: Recipe, recipe2: Recipe): Int {
        val gaps1 = calculateRecipeGodTierGaps(chef, recipe1)
        val gaps2 = calculateRecipeGodTierGaps(chef, recipe2)
        
        // 检查是否为单技法神差值
        val isSingleGap1 = gaps1.size == 1
        val isSingleGap2 = gaps2.size == 1
        
        return when {
            // 如果一个是单技法，另一个是多技法，优先单技法
            isSingleGap1 && !isSingleGap2 -> -1
            !isSingleGap1 && isSingleGap2 -> 1
            
            // 如果都是单技法神差值，按神差值由低到高排序
            isSingleGap1 && isSingleGap2 -> {
                val gap1 = gaps1.values.first()
                val gap2 = gaps2.values.first()
                val gapComparison = gap1.compareTo(gap2)
                if (gapComparison != 0) {
                    gapComparison
                } else {
                    recipe1.time.compareTo(recipe2.time) // 神差值相同时按时间排序
                }
            }
            
            // 如果都是多技法神差值，按每个菜谱神差值最低的那个技法升序排序
            !isSingleGap1 && !isSingleGap2 -> {
                val minGap1 = gaps1.values.minOrNull() ?: Int.MAX_VALUE
                val minGap2 = gaps2.values.minOrNull() ?: Int.MAX_VALUE
                val minGapComparison = minGap1.compareTo(minGap2)
                if (minGapComparison != 0) {
                    minGapComparison
                } else {
                    recipe1.time.compareTo(recipe2.time) // 最小神差值相同时按时间排序
                }
            }
            
            // 其他情况按时间排序
            else -> recipe1.time.compareTo(recipe2.time)
        }
    }
    
    /**
     * 计算菜谱最大制作份数
     */
    private fun calculateMaxPortions(recipe: Recipe, recipeLimits: RecipeLimitsState): Int {
        val basePortions = when (recipe.rarity) {
            1 -> 40
            2 -> 30
            3 -> 25
            4 -> 20
            5 -> 15
            else -> 0
        }
        
        val limitBonus = when (recipe.rarity) {
            1 -> recipeLimits.star1
            2 -> recipeLimits.star2
            3 -> recipeLimits.star3
            4 -> recipeLimits.star4
            5 -> recipeLimits.star5
            else -> 0
        }
        
        return basePortions + limitBonus
    }
    
    /**
     * 计算菜谱达到神级所需的技法差值
     */
    private fun calculateRecipeGodTierGaps(chef: Chef, recipe: Recipe): Map<String, Int> {
        val gaps = mutableMapOf<String, Int>()
        
        // 计算各个技法的差值，返回中文技法名称
        if (recipe.stirfry > 0) {
            val stirfryRequirement = recipe.stirfry * 4
            val deficit = stirfryRequirement - chef.stirfry
            if (deficit > 0) gaps["炒"] = deficit
        }
        if (recipe.boil > 0) {
            val boilRequirement = recipe.boil * 4
            val deficit = boilRequirement - chef.boil
            if (deficit > 0) gaps["煮"] = deficit
        }
        if (recipe.knife > 0) {
            val knifeRequirement = recipe.knife * 4
            val deficit = knifeRequirement - chef.knife
            if (deficit > 0) gaps["切"] = deficit
        }
        if (recipe.fry > 0) {
            val fryRequirement = recipe.fry * 4
            val deficit = fryRequirement - chef.fry
            if (deficit > 0) gaps["炸"] = deficit
        }
        if (recipe.bake > 0) {
            val bakeRequirement = recipe.bake * 4
            val deficit = bakeRequirement - chef.bake
            if (deficit > 0) gaps["烤"] = deficit
        }
        if (recipe.steam > 0) {
            val steamRequirement = recipe.steam * 4
            val deficit = steamRequirement - chef.steam
            if (deficit > 0) gaps["蒸"] = deficit
        }
        
        return gaps
    }
    
    /**
     * 计算厨师在特定技法上的光环加成值
     */
    private fun calculateChefSkillBonus(chef: Chef, skillType: String, skills: List<Skill>): Int {
                if (!chef.hasUltimateSkill()) return 0

        // 将中文技法类型转换为英文
        val englishSkillType = when (skillType) {
            "炒" -> "stirfry"
            "煮" -> "boil"
            "切" -> "knife"
            "炸" -> "fry"
            "烤" -> "bake"
            "蒸" -> "steam"
            else -> skillType
        }

        var total = 0
        chef.getAllUltimateSkills().forEach { sid ->
            val ultimateSkill = skills.find { it.skillId == sid } ?: return@forEach
            val effects = ChefInteractionCalculator.parseSkillDescription(ultimateSkill.desc)
            // 查找PARTIAL类型的技能效果（全场生效的光环）
            total += effects.filter { 
                it.skillType == englishSkillType && 
                it.condition == ChefInteractionCalculator.SkillCondition.PARTIAL 
            }.sumOf { it.value }
        }
        return total
    }
    
    /**
     * 统一计算所有厨师的菜谱份数
     * 在确定最终菜谱组合后调用，确保份数计算正确
     */
    private fun recalculateAllPortions(
        recipes: List<Recipe>,
        chefs: List<Chef>,
        recipeLimits: List<Int>,
        totalRequiredPortions: Int
    ): MutableList<Int> {
        val portions = MutableList(recipes.size) { 0 }
        
        // 全局剩余份数（所有厨师共享）
        var globalRemainingPortions = totalRequiredPortions
        
        // 按厨师分组计算份数
        for (chefIndex in 0 until minOf(chefs.size, 3)) {
            if (chefs[chefIndex].name.isEmpty()) continue
            
            // 计算该厨师的3个菜谱份数
            for (recipeSlot in 0..2) {
                val recipeIndex = chefIndex * 3 + recipeSlot
                if (recipeIndex < recipes.size) {
                    val recipe = recipes[recipeIndex]
                    if (recipe.name.isNotEmpty()) {
                        // 获取单个菜谱的最大份数
                        val maxPortions = calculateMaxPortions(recipe, com.example.show_auto.ui.pages.RecipeLimitsState(recipeLimits[0], recipeLimits[1], recipeLimits[2], recipeLimits[3], recipeLimits[4]))
                        // 实际分配份数 = min(单个菜谱最大份数, 全局剩余份数)
                        val actualPortions = minOf(maxPortions, globalRemainingPortions)
                        portions[recipeIndex] = maxOf(actualPortions, 0) // 确保不为负数
                        globalRemainingPortions -= actualPortions
                    }
                }
            }
        }
        
        return portions
    }

    /**
     * 第4、6、7步：重新评估菜谱
     */
    private fun reevaluateRecipes(
        condition: QuestCondition,
        availableRecipes: List<Recipe>,
        currentChefs: List<Chef>,
        currentEquips: List<Equip>,
        currentRecipes: List<Recipe>,
        targetChefIndex: Int,
        skills: List<Skill>,
        ultimateSkills: UltimateSkillsState,
        recipeLimits: RecipeLimitsState
    ): MutableList<Recipe> {
        
        // 应用厨师间技法影响（使用设置页面的选择）
        val chefInteractions = ChefInteractionCalculator.calculateChefInteractions(currentChefs, skills, currentEnabledAuraChefs)
        
        val targetChef = currentChefs[targetChefIndex]
        val targetEquip = currentEquips.getOrNull(targetChefIndex) ?: Equip()
        
        // 调用菜谱查询接口（使用当前的厨师组合）
        val sortedRecipes = queryRecipesWithInterface(
            condition = condition,
            allRecipes = availableRecipes,
            selectedRecipes = currentRecipes, // 传入当前已选菜谱，避免重复
            currentChefs = currentChefs,
            currentEquips = currentEquips,
            targetChefIndex = targetChefIndex,
            skills = skills,
            ultimateSkills = ultimateSkills,
            onlyShowOwned = true
        )
        
        // 应用所有技法加成
        val enhancedChef = ChefSkillCalculator.applyAllSkills(
            chef = targetChef,
            ultimateSkills = ultimateSkills,
            equip = targetEquip,
            skills = skills,
            chefInteractionBonus = chefInteractions.getOrNull(targetChefIndex)
        )
        
        // 替换未达神级的菜谱（只处理目标厨师的菜谱）
        val updatedRecipes = currentRecipes.toMutableList()
        
        // 只处理目标厨师的3个菜谱位置
        for (i in 0..2) {
            val recipeIndex = targetChefIndex * 3 + i
            if (recipeIndex >= updatedRecipes.size) break
            
            val currentRecipe = updatedRecipes[recipeIndex]
            if (currentRecipe.name.isEmpty()) continue
            
            val currentRank = RecipeRankCalculator.calculateRecipeRank(enhancedChef, currentRecipe)
            if (currentRank < 4) {
                // 寻找能达到神级的替代菜谱（已按星级高→品级高→时间低排序）
                val betterRecipe = sortedRecipes.find { recipe ->
                    val rank = RecipeRankCalculator.calculateRecipeRank(enhancedChef, recipe)
                    rank >= 4 && !updatedRecipes.contains(recipe)
                }
                
                if (betterRecipe != null) {
                    val betterRank = RecipeRankCalculator.calculateRecipeRank(enhancedChef, betterRecipe)
                    updatedRecipes[recipeIndex] = betterRecipe
                }
            }
        }
        
        return updatedRecipes
    }
    
    /**
     * 重新评估菜谱（包括未拥有菜谱，并持久化状态）
     */
    private fun reevaluateRecipesWithUnowned(
        condition: QuestCondition,
        availableRecipes: List<Recipe>,
        currentChefs: List<Chef>,
        currentEquips: List<Equip>,
        currentRecipes: List<Recipe>,
        currentPortions: List<Int>,
        targetChefIndex: Int,
        skills: List<Skill>,
        ultimateSkills: UltimateSkillsState,
        recipeLimits: RecipeLimitsState,
        settingsStorage: com.example.show_auto.data.SettingsStorage
    ): RecipeAllocation {
        
        
        // 应用厨师间技法影响（使用设置页面的选择）
        val chefInteractions = ChefInteractionCalculator.calculateChefInteractions(currentChefs, skills, currentEnabledAuraChefs)
        
        val targetChef = currentChefs[targetChefIndex]
        val targetEquip = currentEquips.getOrNull(targetChefIndex) ?: Equip()
        
        // 调用菜谱查询接口（设置onlyShowOwned = false以包括未拥有菜谱）
        val sortedRecipes = queryRecipesWithInterface(
            condition = condition,
            allRecipes = availableRecipes,
            selectedRecipes = currentRecipes, // 传入当前已选菜谱，避免重复
            currentChefs = currentChefs,
            currentEquips = currentEquips,
            targetChefIndex = targetChefIndex,
            skills = skills,
            ultimateSkills = ultimateSkills,
            onlyShowOwned = false // 关键修改：包括未拥有菜谱
        )
        
        // 应用所有技法加成
        val enhancedChef = ChefSkillCalculator.applyAllSkills(
            chef = targetChef,
            ultimateSkills = ultimateSkills,
            equip = targetEquip,
            skills = skills,
            chefInteractionBonus = chefInteractions.getOrNull(targetChefIndex)
        )
        
        // 替换未达神级的菜谱（只处理目标厨师的菜谱）
        val updatedRecipes = currentRecipes.toMutableList()
        val updatedPortions = currentPortions.toMutableList()
        var hasUsedUnownedRecipes = false
        
        
        // 计算任务需要的总份数
        val totalRequiredPortions = condition.num
        
        // 只处理目标厨师的3个菜谱位置
        for (i in 0..2) {
            val recipeIndex = targetChefIndex * 3 + i
            if (recipeIndex >= updatedRecipes.size) {
                break
            }
            
            val currentRecipe = updatedRecipes[recipeIndex]
            val needsReplacement = if (currentRecipe.name.isEmpty()) {
                true
            } else {
                val currentRank = RecipeRankCalculator.calculateRecipeRank(enhancedChef, currentRecipe)
                currentRank < 4
            }
            
            if (needsReplacement) {
                // 寻找能达到神级的替代菜谱（已按星级高→品级高→时间低排序）
                val betterRecipe = sortedRecipes.find { recipe ->
                    val rank = RecipeRankCalculator.calculateRecipeRank(enhancedChef, recipe)
                    rank >= 4 && !updatedRecipes.contains(recipe)
                }
                
                if (betterRecipe != null) {
                    val betterRank = RecipeRankCalculator.calculateRecipeRank(enhancedChef, betterRecipe)
                    val ownedStatus = if (betterRecipe.got) "已有" else "未拥有"
                    
                    if (currentRecipe.name.isEmpty()) {
                    } else {
                        val currentRank = RecipeRankCalculator.calculateRecipeRank(enhancedChef, currentRecipe)
                    }
                    
                    updatedRecipes[recipeIndex] = betterRecipe
                    
                    // 计算该菜谱的份数
                    val maxPortions = calculateMaxPortions(betterRecipe, recipeLimits)
                    
                    // 如果是为空位置分配菜谱，需要重新计算份数分配
                    if (currentRecipe.name.isEmpty()) {
                        // 计算已分配的份数
                        val allocatedPortions = (0..2).sumOf { j ->
                            val idx = targetChefIndex * 3 + j
                            if (idx < updatedPortions.size && idx != recipeIndex) {
                                updatedPortions[idx]
                            } else 0
                        }
                        
                        // 计算剩余需要的份数
                        val remainingPortions = totalRequiredPortions - allocatedPortions
                        val assignedPortions = minOf(remainingPortions, maxPortions)
                        
                        updatedPortions[recipeIndex] = assignedPortions
                    } else {
                        // 保持原有份数或重新计算
                        val currentPortionValue = if (recipeIndex < updatedPortions.size) updatedPortions[recipeIndex] else maxPortions
                        updatedPortions[recipeIndex] = minOf(currentPortionValue, maxPortions)
                    }
                    
                    // 如果使用了未拥有菜谱，记录状态
                    if (!betterRecipe.got) {
                        hasUsedUnownedRecipes = true
                    }
                } else {
                }
            }
        }
        
        // 如果使用了未拥有菜谱，持久化"查询已有"状态为false
        if (hasUsedUnownedRecipes) {
            try {
                settingsStorage.saveFilterOwnedRecipes(false)
            } catch (e: Exception) {
            }
        }
        
        return RecipeAllocation(updatedRecipes, updatedPortions, emptyList())
    }
    


    /**
     * 判断菜谱是否可以通过厨具达到神级
     */
    private fun canReachGodTierWithEquip(chef: Chef, recipe: Recipe, usePowerfulEquips: Boolean): Boolean {
        val gaps = calculateRecipeGodTierGaps(chef, recipe)
        if (gaps.isEmpty()) return true // 已经是神级
        
        // 检查是否只有一种技法缺失
        if (gaps.size != 1) return false
        
        val gapValue = gaps.values.first()
        return if (usePowerfulEquips) {
            gapValue > 100 && gapValue <= 200
        } else {
            gapValue <= 100
        }
    }

    /**
     * 判断厨具是否为强力厨具（任意技法加成 > 100）
     */
    private fun isPowerfulEquip(equip: Equip, skills: List<Skill>): Boolean {
        for (skillId in equip.skill) {
            val skill = skills.find { it.skillId == skillId }
            if (skill != null) {
                val skillDesc = skill.desc
                
                // 检查各种技法加成
                val skillPatterns = listOf(
                    "炒技法([+\\-]?\\d+)".toRegex(),
                    "煮技法([+\\-]?\\d+)".toRegex(),
                    "切技法([+\\-]?\\d+)".toRegex(),
                    "炸技法([+\\-]?\\d+)".toRegex(),
                    "烤技法([+\\-]?\\d+)".toRegex(),
                    "蒸技法([+\\-]?\\d+)".toRegex(),
                    "全技法([+\\-]?\\d+)".toRegex()
                )
                
                for (pattern in skillPatterns) {
                    val match = pattern.find(skillDesc)
                    if (match != null) {
                        val value = match.groupValues[1].toIntOrNull() ?: 0
                        if (value > 100) {
                            return true
                        }
                    }
                }
            }
        }
        return false
    }

    /**
     * 第5步：厨具推荐补强（已有和可能已有厨具）
     */
    private fun enhanceWithAvailableEquips(
        currentChefs: List<Chef>,
        currentEquips: MutableList<Equip>,
        currentRecipes: List<Recipe>,
        allEquips: List<Equip>,
        skills: List<Skill>,
        allChefs: List<Chef>,
        allRecipes: List<Recipe>,
        targetChefIndex: Int,
        ultimateSkills: UltimateSkillsState,
        settingsStorage: com.example.show_auto.data.SettingsStorage
    ) {
        val targetChef = currentChefs[targetChefIndex]
        val targetEquip = currentEquips.getOrNull(targetChefIndex) ?: Equip()
        
        // 计算厨师间技法影响（使用设置页面的选择，包含第三步PARTIAL厨师补强后的完整组合）
        val chefInteractions = ChefInteractionCalculator.calculateChefInteractions(currentChefs, skills, currentEnabledAuraChefs)
        
        // 应用所有技法加成到厨师（包含第三步后的光环加成）
        val enhancedChef = ChefSkillCalculator.applyAllSkills(
            chef = targetChef,
            ultimateSkills = ultimateSkills,
            equip = targetEquip,
            skills = skills,
            chefInteractionBonus = chefInteractions.getOrNull(targetChefIndex)
        )
        
        val targetRecipes = listOf(
            currentRecipes.getOrNull(targetChefIndex * 3),
            currentRecipes.getOrNull(targetChefIndex * 3 + 1),
            currentRecipes.getOrNull(targetChefIndex * 3 + 2)
        ).filterNotNull().filter { it.name.isNotEmpty() }
        
        if (targetRecipes.isNotEmpty()) {
            // 过滤厨具：已有和可能已有的，根据配置决定是否排除强力厨具
            val filteredEquips = allEquips.filter { equip ->
                val isAvailable = isEquipAvailable(equip, allRecipes)
                val isPowerful = isPowerfulEquip(equip, skills)
                val usePowerfulEquips = settingsStorage.getUsePowerfulEquips()
                
                isAvailable && (usePowerfulEquips || !isPowerful)
            }
            
            val recommendation = calculateEquipRecommendationForOneClick(
                chef = enhancedChef, // 使用增强后的厨师
                recipes = targetRecipes,
                allEquips = filteredEquips,
                skills = skills,
                allChefs = allChefs,
                allRecipes = allRecipes
            )
            
            if (recommendation.recommendedEquips.isNotEmpty()) {
                val selectedEquip = recommendation.recommendedEquips.first().equip
                currentEquips[targetChefIndex] = selectedEquip
            }
        }
    }
    
    /**
     * 第7步：厨具推荐补强（所有厨具）
     */
    private fun enhanceWithAnyEquips(
        currentChefs: List<Chef>,
        currentEquips: MutableList<Equip>,
        currentRecipes: List<Recipe>,
        allEquips: List<Equip>,
        skills: List<Skill>,
        allChefs: List<Chef>,
        allRecipes: List<Recipe>,
        targetChefIndex: Int,
        ultimateSkills: UltimateSkillsState,
        settingsStorage: com.example.show_auto.data.SettingsStorage
    ) {
        val targetChef = currentChefs[targetChefIndex]
        
        // 计算厨师间技法影响（使用设置页面的选择，包含第三步PARTIAL厨师补强后的完整组合）
        val chefInteractions = ChefInteractionCalculator.calculateChefInteractions(currentChefs, skills, currentEnabledAuraChefs)
        
        // 应用所有技法加成到厨师（包含第三步后的光环加成，但不包含当前厨具）
        val enhancedChef = ChefSkillCalculator.applyAllSkills(
            chef = targetChef,
            ultimateSkills = ultimateSkills,
            equip = null, // 不包含厨具，因为推荐算法会自己测试厨具
            skills = skills,
            chefInteractionBonus = chefInteractions.getOrNull(targetChefIndex)
        )
        
        val targetRecipes = listOf(
            currentRecipes.getOrNull(targetChefIndex * 3),
            currentRecipes.getOrNull(targetChefIndex * 3 + 1),
            currentRecipes.getOrNull(targetChefIndex * 3 + 2)
        ).filterNotNull().filter { it.name.isNotEmpty() }
        
        
        if (targetRecipes.isNotEmpty()) {
            // 过滤厨具：根据配置决定是否排除强力厨具
            val filteredEquips = if (settingsStorage.getUsePowerfulEquips()) {
                allEquips // 使用所有厨具
            } else {
                allEquips.filter { equip ->
                    !isPowerfulEquip(equip, skills) // 排除强力厨具
                }
            }
            
            val recommendation = calculateEquipRecommendationForOneClick(
                chef = enhancedChef, // 使用增强后的厨师
                recipes = targetRecipes,
                allEquips = filteredEquips,
                skills = skills,
                allChefs = allChefs,
                allRecipes = allRecipes
            )
            
            if (recommendation.recommendedEquips.isNotEmpty()) {
                val selectedEquip = recommendation.recommendedEquips.first().equip
                currentEquips[targetChefIndex] = selectedEquip
            }
        }
    }
    
    /**
     * 检查厨具是否为已有或可能已有
     */
    private fun isEquipAvailable(equip: Equip, allRecipes: List<Recipe>): Boolean {
        val equipOrigins = equip.origin.replace("<br>", "、").split("、").map { it.trim() }
        
        // 检查是否包含奖池来源
        val hasPoolOrigin = equipOrigins.any { origin ->
            origin.contains("新手奖池") || 
            origin.contains("中级奖池") || 
            origin.contains("高级奖池") || 
            origin.contains("碧池")
        }
        
        if (hasPoolOrigin) return true
        
        // 检查是否包含默认可能拥有的来源
        val hasDefaultPossibleOrigin = equipOrigins.any { origin ->
            origin.contains("实验室") || origin.contains("厨神")
        }
        
        if (hasDefaultPossibleOrigin) return true
        
        // 检查是否有已获得的菜谱来源包含厨具任一来源
        return equipOrigins.any { equipOrigin ->
            allRecipes.any { recipe ->
                recipe.got && recipe.origin.contains(equipOrigin)
            }
        }
    }
    
    /**
     * 扩展到9个菜谱（每个厨师3个）
     */
    private fun expandToNineRecipes(recipes: List<Recipe>): List<Recipe> {
        val result = mutableListOf<Recipe>()
        
        // 第一个厨师的菜谱（0, 1, 2）
        repeat(3) { i ->
            result.add(recipes.getOrNull(i) ?: Recipe())
        }
        
        // 第二个厨师的菜谱（3, 4, 5）
        repeat(3) { i ->
            result.add(Recipe()) // 暂时为空，因为其他厨师还没有专门的菜谱分配逻辑
        }
        
        // 第三个厨师的菜谱（6, 7, 8）
        repeat(3) { i ->
            result.add(Recipe()) // 暂时为空
        }
        
        return result
    }
    
    /**
     * 扩展到3个厨具
     */
    private fun expandToThreeEquips(equips: List<Equip>): List<Equip> {
        val result = mutableListOf<Equip>()
        repeat(3) { i ->
            result.add(equips.getOrNull(i) ?: Equip())
        }
        return result
    }
    
    /**
     * 获取菜谱的技法信息
     */
    private fun getRecipeSkills(recipe: Recipe): String {
        val skills = mutableListOf<String>()
        if (recipe.stirfry > 0) skills.add("炒${recipe.stirfry}")
        if (recipe.boil > 0) skills.add("煮${recipe.boil}")
        if (recipe.knife > 0) skills.add("切${recipe.knife}")
        if (recipe.fry > 0) skills.add("炸${recipe.fry}")
        if (recipe.bake > 0) skills.add("烤${recipe.bake}")
        if (recipe.steam > 0) skills.add("蒸${recipe.steam}")
        return skills.joinToString(",")
    }
} 